var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var adminRouter = require('./routes/admin');
var usersRouter = require('./routes/users');
var wxRouter = require('./routes/wxRouter');
var book = require('./routes/book')

var app = express();
// 解决跨域问题
app.all("/*", function(req, res, next) {
  // 跨域处理
  let arr = ['wx6820760b1be48361','wx903ced0972fe109c','wx812010c2d282bb0a','wx2a4c068c60369ceb']
  let referer = req.headers['referer']||req.headers['referered']
  if(referer){
    let flag = true
    arr.forEach(item=>{
      if(referer.match(item)){
        flag = false
      }
    })
    if(flag){
      res.send('无访问权限')
    }
  }
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1');
  res.header("Content-Type", "application/json;charset=utf-8");
  next(); // 执行下一个路由
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/admin', adminRouter);
app.use('/users', usersRouter);
app.use('/weixin',wxRouter)
app.use('/book',book)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
